package com.lunatic.rocketmq.demo;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.client.producer.SendResult;

public class RocketMQProducer {
    public static void main(String[] args) throws Exception {
        // 1. 初始化生产者
        DefaultMQProducer producer = new DefaultMQProducer(
                "producer_group");
        producer.setNamesrvAddr("192.168.101.106:9876");
        producer.setMaxMessageSize(100);
        producer.start();

        // 2. 发送消息（使用 Java 17 特性：var 关键字）
        for (int i = 0; i < 2; i++) {
            var msg = new Message(
                    "TestTopic",
                    "TagA",
                    ("Hello RocketMQ " + i).getBytes());


            // 同步发送，需要等待broker确认
            SendResult result = producer.send(msg);
            System.out.printf("Sent message: %s%n", result);

            // 异步发送, 效率更高
//            producer.send(msg, new SendCallback() {
//                @Override
//                public void onSuccess(SendResult sendResult) {
//                    System.out.println(sendResult.getOffsetMsgId() + sendResult.getSendStatus());
//                }
//
//                @Override
//                public void onException(Throwable throwable) {
//                    System.out.println(throwable.getMessage());
//                }
//            });

        }
        System.out.println("over");
        System.in.read();

        // 3. 关闭生产者
        producer.shutdown();
    }
}